package com.dhecp.project.common.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTableToEntity;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.domain.SysDictionaryRelationForField;
import com.dhecp.project.system.domain.SysDictionaryRelationForModule;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysDictionaryRelationForFieldService;
import com.dhecp.project.system.service.SysDictionaryRelationForModuleService;

/**
 * 调入页面 控制层
 * @author DH-Xxj
 * @version 2019年12月3日
 */
@Controller
@RequestMapping("/common/relation")
public class FoldRelationController extends BaseController {

	private String prefix = "common/relation";

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;
    
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

	@Autowired
    private SysDictionaryRelationForModuleService dictionaryRelationForModuleService;
	
	@Autowired
	private SysDictionaryRelationForFieldService dictionaryRelationForFieldService;

    /**
     * 打开调入页面
     * @param relationguid 必要参数：调入关系主键[guid]
     * @return ModelAndView
     * @author DH-Xxj
     */
	@GetMapping("/relationpage")
    public ModelAndView foldRelationPage(@RequestParam Map<String, Object> params){
		ModelAndView mv = this.getModelAndView();
		mv = this.gotoModelAndViewErrorPage(params, "relationguid", "调入关系主键[guid]");
		if (!mv.isEmpty()){
			return mv;
		}
		String relationguid = params.get("relationguid").toString();
		SysDictionaryRelationForModule relationForModule = dictionaryRelationForModuleService.queryDictionaryRelationForModuleByGuid(relationguid);
		if (relationForModule == null){
			AjaxResult ajaxResult = AjaxResult.error("未查询到调入关系");
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName("error/mv_error");
            return mv;
		}
		
		String dataUrl = "";
		if (relationForModule.getSourceDataurl() == null || "".equals(relationForModule.getSourceDataurl().toString())){
			AjaxResult ajaxResult = AjaxResult.error("未设置调入数据地址");
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName("error/mv_error");
            return mv;
		}else{
			dataUrl = relationForModule.getSourceDataurl().toString();
		}
		if (relationguid != null && !"".equals(relationguid)){
			dataUrl = dataUrl + "?relationguid=" + relationguid;
		}
		
		String moduleTable = "";
		String moduleTableEntity = "";
		if (relationForModule.getsModuleTableField() != null && !"".equals(relationForModule.getsModuleTableField())){
			moduleTable = relationForModule.getsModuleTableField();
		}else if (relationForModule.getsModuleTable() != null && !"".equals(relationForModule.getsModuleTable())){
			moduleTable = relationForModule.getsModuleTable();
		}else{
			moduleTable = "moduleTable";
		}
		if (relationForModule.getsModuleTable() != null && !"".equals(relationForModule.getsModuleTable())){
			moduleTableEntity = relationForModule.getsModuleTable();
		}else{
			moduleTableEntity = "moduleTable";
		}
		params.put("moduleTable", moduleTable);
		
		Object entity = ModuleTableToEntity.queryEntityByModuleTable(moduleTableEntity).get("entity");

		params.put("entity", entity);
		params.put("checkBox", "yes"); //生成表格gridColumns时包含复选

    	if (params.get("toolBarWidth") == null || params.get("toolBarWidth") == ""){	//默认不生成操作区宽度
    		params.put("toolBarWidth", 0);
    	}
    	params.put("getFieldAttributesType", "pagecallin");
		Map<String, Object> gridColumns = gridColumnsPropertyModel.queryGridColumnsPropertyModel(params);
    	
		Object foldRelation = getRelationForField(params.get("relationguid").toString(), relationForModule);

		mv.addObject("gridColumns", gridColumns);
		mv.addObject("foldRelation", foldRelation);
		mv.addObject("dataUrl", dataUrl + "&moduleTable=" + moduleTable + "&moduleTableEntity=" + moduleTableEntity);
		mv.addObject("moduleTable", moduleTable);
		mv.addObject("moduleTableEntity", moduleTableEntity);
        mv.setViewName(prefix + "/relation");
		return mv;
    }
	
	/**
	 * 字段调入关系
	 * @param pguid 必要参数：调入关系GUID
	 * @param relationForModule 必要参数：调入关系功能实体
	 * @return jsion
	 * @author DH-Xxj
	 */
	public Object getRelationForField(String pguid, SysDictionaryRelationForModule relationForModule){
		Object foldRelation = null;
		Map<String, Object> foldRelationMap = new HashMap<String, Object>();
		Map<String, Object> foldRelationHeadMap = new HashMap<String, Object>();
		Map<String, Object> foldRelationHeadNameMap = new HashMap<String, Object>();
		Map<String, Object> foldRelationGridMap = new HashMap<String, Object>();
		Map<String, Object> bFieldKeysMap = new HashMap<String, Object>();
		Map<String, Object> headParams = new HashMap<String, Object>();
		Map<String, Object> headFieldsMap = new HashMap<String, Object>();
		List<SysDictionaryRelationForField> dicRelationForFieldList = dictionaryRelationForFieldService.queryDictionaryRelationForFieldByPguid(pguid);
		Object sEntity = ModuleTableToEntity.queryEntityByModuleTable(relationForModule.getsModuleTable().toString()).get("entity"); //源实体实例
		Object rEntity = ModuleTableToEntity.queryEntityByModuleTable(relationForModule.getrModuleTable().toString()).get("entity"); //目标实体实例
    	Map<String, Object> sEntityFieldMap = TypeUtils.entityFieldsToMap(sEntity);
    	Map<String, Object> rEntityFieldMap = TypeUtils.entityFieldsToMap(rEntity);

    	headParams.put("moduleTable", relationForModule.getrModuleTable().toString()); //目标功能唯一标识
    	headParams.put("entity", rEntityFieldMap); //目标实体实例
    	headParams.put("getFieldAttributesType", "pagenotingrid"); 	//制单页面非网格字段
    	List<SysDictionaryForPageField> headFieldsList = dictionaryForFieldService.queryFieldAttributesList(headParams);
    	for (SysDictionaryForPageField headField : headFieldsList){
    		headFieldsMap.put(headField.getFields().toString().toLowerCase(), headField.getFields().toString());
    	}
    	
		for (SysDictionaryRelationForField relationField : dicRelationForFieldList){
			String sField = relationField.getsFields(); //源字段
			String rField = relationField.getrFields(); //目标字段
			Boolean bFieldKeys=relationField.getbFieldKeys();//主键列
            if (sEntityFieldMap.get(sField.toLowerCase()) != null && !"".equals(sEntityFieldMap.get(sField.toLowerCase()))){
            	sField = sEntityFieldMap.get(sField.toLowerCase()).toString();
            }
            if (rEntityFieldMap.get(rField.toLowerCase()) != null && !"".equals(rEntityFieldMap.get(rField.toLowerCase()))){
            	rField = rEntityFieldMap.get(rField.toLowerCase()).toString();
            }
            if(bFieldKeys){
            	bFieldKeysMap.put(sField,rField);
            }
            if (headFieldsMap.get(rField.toLowerCase()) == null){ //调入明细
            	foldRelationGridMap.put(rField, sField);//一对多，源和目标对调
            }else{ //调入表头
            	foldRelationHeadMap.put(rField, sField);//一对多,源和目标对调
            	foldRelationHeadNameMap.put(sField, relationField.getsFieldName());
            }
		}
		foldRelationMap.put("bFieldKeys", TypeUtils.mapToJson(bFieldKeysMap));
		foldRelationMap.put("headFieldNames", TypeUtils.mapToJson(foldRelationHeadNameMap));
		foldRelationMap.put("headFields", TypeUtils.mapToJson(foldRelationHeadMap));
		foldRelationMap.put("gridFields", TypeUtils.mapToJson(foldRelationGridMap));
		foldRelation = TypeUtils.mapToJson(foldRelationMap);
		return foldRelation;
	}
	
}
